package com.springdoor.web.controller.common;

import com.springdoor.common.core.domain.AjaxResult;
import com.springdoor.common.utils.QiNiuUtils;
import com.springdoor.common.utils.file.FileUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/qncommon")
public class QiniuUploadController {

    private static final Logger log = LoggerFactory.getLogger(QiniuUploadController.class);

    @Autowired
    private QiNiuUtils qiNiuUtils;

    @PostMapping("/upload")
    @ApiOperation(value = "上传下载图片")
    public AjaxResult imageUpload(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            //判断文件格式是否为图片
            if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jepg")){
                String fileName = file.getName();
                String fileUrl = qiNiuUtils.uploadImageQiniu(file);
                if (StringUtils.isBlank(fileUrl)) {
                    return AjaxResult.error("文件上传错误.");
                }
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", fileUrl);
                ajax.put("fileName", fileUrl);
                return ajax;
            }
            return AjaxResult.error("文件格式错误.");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
